package com.chen.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.blog.common.api.CommonResult;
import com.chen.blog.common.constant.MessageConstant;
import com.chen.blog.mapper.ScoreMapper;
import com.chen.blog.model.Score;
import com.chen.blog.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chen
 * @since 2022-01-24
 */
@Service
@Transactional
public class ScoreServiceImpl extends ServiceImpl<ScoreMapper, Score> implements ScoreService {

    @Autowired
    private ScoreMapper scoreMapper;

    /**
     * 获取不同分数区间下的博客数量功能实现
     *
     * @return
     */
    @Override
    public Map<String, Object> findBlogByScore() {
        return scoreMapper.findBlogByScore();
    }

    /**
     * 新增博客评分功能实现
     *
     * @param score
     * @return
     */
    @Override
    public CommonResult addScore(Score score) {
        Score realScore = scoreMapper.selectOne(new QueryWrapper<Score>().eq("blog_id", score.getBlogId()).eq("user_id", score.getUserId()));
        if (realScore != null) {
            //说明用户在评分以评分过的博客，则进行评分的更新
            score.setId(realScore.getId());
            if (scoreMapper.updateById(score) == 1) {
                return CommonResult.success(MessageConstant.ADD_SCORE_SUCCESS);
            }
            return CommonResult.error(MessageConstant.ADD_POSITION_FAIL);
        }
        if (scoreMapper.insert(score) == 1) {
            return CommonResult.success(MessageConstant.ADD_SCORE_SUCCESS);
        }
        return CommonResult.error(MessageConstant.ADD_SCORE_FAIL);
    }
}
